package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.AmazonReimbursements;
import com.fowo.api.entity.TmpReimbursements;
import com.fowo.api.mapper.AmazonReimbursementsMapper;
import com.fowo.api.mapper.TmpReimbursementsMapper;
import com.fowo.api.syncAmazon.api.ReimbursementsReportService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReimbursementsServiceImpl extends ServiceImpl<AmazonReimbursementsMapper, AmazonReimbursements> {

    @Resource
    private TmpReimbursementsMapper tmpReimbursementsMapper;
    @Resource
    private ReimbursementsReportService reportService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    /**
     * 同步临时表数据
     *
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncReimbursements() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllReimbursements();
        //拉取亚马逊赔偿数据
        reportService.getReimbursements();
        List<AmazonReimbursements> insertList = new ArrayList<>();
        //获取临时表数据
        List<TmpReimbursements> tmpReimbursements = tmpReimbursementsMapper.selectList(new QueryWrapper<>());
        //组装数据
        if (tmpReimbursements != null && tmpReimbursements.size() > 0) {
            for (TmpReimbursements reimbursements : tmpReimbursements) {
                //重复校验
                QueryWrapper<AmazonReimbursements> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("reimbursement_id",reimbursements.getReimbursementId());
                int count = (int)this.count(queryWrapper);
                if(count > 0){
                    continue;
                }
                AmazonReimbursements amazonReimbursements = new AmazonReimbursements();
                BeanUtils.copyProperties(reimbursements, amazonReimbursements);
                amazonReimbursements.setId(null);
                amazonReimbursements.setCreateTime(new Date());
                insertList.add(amazonReimbursements);
            }
            //分批次插入
            List<List<AmazonReimbursements>> partition = Lists.partition(insertList, 200);
            for (List<AmazonReimbursements> amazonReimbursementsList : partition) {
                this.saveBatch(amazonReimbursementsList);
            }
        }
    }

}
